
import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from xiaochengxu.extensions.time_stamp import get_time_now
from xiaochengxu import models


class OpenId:
    def __init__(self, jscode):
        self.url = 'https://api.weixin.qq.com/sns/jscode2session'
        self.app_id = 'wx4448a0c7c9d306e8'
        self.app_secret = '14a3cd8963ad34df86a1f0917ef0c667'
        self.jscode = jscode

    def get_openid(self):
        url = self.url + "?appid=" + self.app_id + "&secret=" + self.app_secret + "&js_code=" + self.jscode + "&grant_type=authorization_code"
        res = requests.get(url)
        print(res.json())
        try:
            openid = res.json()['openid']
            session_key = res.json()['session_key']
        except KeyError:
            return 'fail'
        else:
            return openid, session_key


class GetOpenId(APIView):
    authentication_classes = []
    def post(self, request, *args, **kwargs):
        jscode = request.data['code']

        openid, session_key = OpenId(jscode).get_openid()

        return Response({
            'openid': openid,
            'session_key': session_key
        })


class Login(APIView):
    authentication_classes = []
    def post(self, request, *args, **kwargs):
        data = request.data
        openid = data['openid']
        session_key = data['session_key']
        nickname = data['nickname']
        avatar_url = data['avatar_url']
        gender = data['gender']

        try:
            user = models.User.objects.get(openid=openid)
        except models.User.DoesNotExist:
            user = None

        if user:
            user = models.User.objects.get(openid=openid)
        else:
            user = models.User.objects.create(
                username=openid,
                password=openid,
                nickname=nickname,
                session_key=session_key,
                openid=openid,
                creat_time=get_time_now(),
                update_time=get_time_now(),
            )
            models.User_info.objects.create(
                uid=user.id,
                nickname=nickname,
                avatar_url=avatar_url,
                gender=gender,
                creat_time=get_time_now(),
                update_time=get_time_now(),
            )

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        res = {
            'status': 'success',
            'nickname': user.nickname,
            'user_id': user.id,
            'token': token,
            'avatar_url': avatar_url
        }
        return Response(res)



